package it.koutifaris.travianmap.mapsqlparser;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMapSqlParser extends AbstractMapSqlParser implements MapSqlParser {

	protected final String TAG = this.getClass().getName();

	private static final String PARSING_REGEX = "(-?\\d+)|'(.*?)'|'()'";
	private static final Pattern PATTERN = Pattern.compile(PARSING_REGEX);

	private final EntryBuilder entryBuilder = new EntryBuilder();

	@Override
	protected MapSqlEntry parseLine(String line) throws SqlParserException {
		try {
			Matcher matcher = PATTERN.matcher(line);
			entryBuilder.clear();
			while (matcher.find()) {
				String value = null;
				for (int i = 1; i <= matcher.groupCount(); i++) {
					value = matcher.group(i);
					if (value != null) {
						break;
					}
				}

				entryBuilder.addValue(value);
			}

			return entryBuilder.build();
		} catch (Exception e) {
			throw new SqlParserException("Error while parsing " + line, e);
		}
	}

}
